package com.jiaobuchong.zookeeper;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author zhoujie
 * Created on 2019-01-20 18:19
 */
public class ZkDistributeLock implements Lock {

    private String lockPath;

    private ZkClient client;

    public ZkDistributeLock(String lockPath) {
        super();
        this.lockPath = lockPath;
        client = new ZkClient("localhost:2181");
        client.setZkSerializer(new MyZkSerializer());
    }

    @Override
    public void lock() {
        // 如果获取不到锁，阻塞等待
        if (!tryLock()) {
            // 获取锁，阻塞自己
            waitForLock();
            // 再次尝试
            lock();
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        // 不会阻塞
        // 创建节点
        try {
            client.createEphemeral(lockPath);
        } catch (ZkNodeExistsException e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        client.delete(lockPath);
    }

    @Override
    public Condition newCondition() {
        return null;
    }

    private void waitForLock() {
        CountDownLatch cdl = new CountDownLatch(1);
        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println("----收到节点数据变化：" + o + "---");
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println("----收到节点被删除了----");
                cdl.countDown();
            }
        };
        client.subscribeDataChanges(lockPath, listener);

        // 阻塞自己
        if (this.client.exists(lockPath)) {
            try {
                cdl.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
